/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.system.service.impl;

import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import lombok.Data;
import me.zhengjie.constant.ConstantUtils;
import me.zhengjie.modules.system.domain.CourseApplicants;
import me.zhengjie.modules.system.domain.CourseApplicantsMain;
import me.zhengjie.modules.web.enums.ApplicantsSignStatusEnum;
import me.zhengjie.modules.web.service.mybatisplus.ICourseApplicantsPlusService;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.system.repository.CourseApplicantsMainRepository;
import me.zhengjie.modules.system.service.CourseApplicantsMainService;
import me.zhengjie.modules.system.service.dto.CourseApplicantsMainDto;
import me.zhengjie.modules.system.service.dto.CourseApplicantsMainQueryCriteria;
import me.zhengjie.modules.system.service.mapstruct.CourseApplicantsMainMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;

import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author wangyu
* @date 2024-05-22
**/
@Service
@RequiredArgsConstructor
public class CourseApplicantsMainServiceImpl implements CourseApplicantsMainService {

    private final CourseApplicantsMainRepository courseApplicantsMainRepository;
    private final CourseApplicantsMainMapper courseApplicantsMainMapper;

    @Autowired
    private ICourseApplicantsPlusService applicantsPlusService;

    @Override
    public Map<String,Object> queryAll(CourseApplicantsMainQueryCriteria criteria, Pageable pageable){
        criteria.setPaid(ConstantUtils.Order_Payed);
        Page<CourseApplicantsMain> page = courseApplicantsMainRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        Map<String, Object> resultMap = PageUtil.toPage(page.map(courseApplicantsMainMapper::toDto));
        if (MapUtil.isEmpty(resultMap) || Objects.isNull(resultMap.get("content"))) {
            return resultMap;
        }
        List<CourseApplicantsMainDto> applicantsMainDtoList = (List<CourseApplicantsMainDto>) resultMap.get("content");
        if (CollectionUtils.isEmpty(applicantsMainDtoList)){
            return resultMap;
        }
        ApplicantsStatistics statistics = new ApplicantsStatistics();
        int online=0 , offline=0 , notCheck=0 , total=0 , expire=0;
        for (CourseApplicantsMainDto courseApplicantsMainDto : applicantsMainDtoList) {
            LambdaQueryWrapper<CourseApplicants> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(CourseApplicants::getOrderNo,courseApplicantsMainDto.getOrderNo());
            List<CourseApplicants> list = applicantsPlusService.list(wrapper);
            courseApplicantsMainDto.setApplicantsList(list);
            if (CollectionUtils.isNotEmpty(list)){
                total += list.size();
                online += list.parallelStream().filter(s -> s.getSignStatus().equals(ApplicantsSignStatusEnum.OnLine.getSignStatus())).count();
                offline += list.parallelStream().filter(s -> s.getSignStatus().equals(ApplicantsSignStatusEnum.OffLine.getSignStatus())).count();
                notCheck += list.parallelStream().filter(s -> s.getSignStatus().equals(ApplicantsSignStatusEnum.NotSign.getSignStatus())).count();
                expire += list.parallelStream().filter(s -> s.getSignStatus().equals(ApplicantsSignStatusEnum.Expired.getSignStatus())).count();
            }
        }
        statistics.setTotal(total);
        statistics.setOnlineTotal(online);
        statistics.setOfflineTotal(offline);
        statistics.setExpireTotal(expire);
        statistics.setNotCheckTotal(notCheck);
        statistics.setCheckTotal(online+offline);
        resultMap.put("statistics",statistics);
        return resultMap;
    }

    @Data
    public static class ApplicantsStatistics{
        //展示数据：当前课程实际总人数，线上签到人数，线下补录人数，未签到记录上课人员姓名和报课人员姓名，各推荐人名下实际来上课人员名单
        /**
         * 总人数
         */
        private int total;
        /**
         * 已签到总人数
         */
        private int checkTotal;
        /**
         * 线上签到人数
         */
        private int onlineTotal;
        /**
         * 线下签到人数
         */
        private int offlineTotal;
        /**
         * 过期签到人数
         */
        private int expireTotal;
        /**
         * 未签到人数
         */
        private int notCheckTotal;
    }
    @Override
    public List<CourseApplicantsMainDto> queryAll(CourseApplicantsMainQueryCriteria criteria){
        return courseApplicantsMainMapper.toDto(courseApplicantsMainRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public CourseApplicantsMainDto findById(Long id) {
        CourseApplicantsMain courseApplicantsMain = courseApplicantsMainRepository.findById(id).orElseGet(CourseApplicantsMain::new);
        ValidationUtil.isNull(courseApplicantsMain.getId(),"CourseApplicantsMain","id",id);
        return courseApplicantsMainMapper.toDto(courseApplicantsMain);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CourseApplicantsMainDto create(CourseApplicantsMain resources) {
        return courseApplicantsMainMapper.toDto(courseApplicantsMainRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(CourseApplicantsMain resources) {
        CourseApplicantsMain courseApplicantsMain = courseApplicantsMainRepository.findById(resources.getId()).orElseGet(CourseApplicantsMain::new);
        ValidationUtil.isNull( courseApplicantsMain.getId(),"CourseApplicantsMain","id",resources.getId());
        courseApplicantsMain.copy(resources);
        courseApplicantsMainRepository.save(courseApplicantsMain);
    }

    @Override
    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            courseApplicantsMainRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<CourseApplicantsMainDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (CourseApplicantsMainDto courseApplicantsMain : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("购买人微信openId", courseApplicantsMain.getOpenId());
            map.put("昵称", courseApplicantsMain.getNickName());
            map.put("真实姓名", courseApplicantsMain.getRealName());
            map.put("手机号", courseApplicantsMain.getMobile());
            map.put("课程编号", courseApplicantsMain.getCourseNo());
            map.put("课程名称", courseApplicantsMain.getCourseName());
            map.put("订单号", courseApplicantsMain.getOrderNo());
            map.put("创建时间", courseApplicantsMain.getCreateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}